/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.prod;

import dp1.titandevelop.titano.bean.Estado;
import dp1.titandevelop.titano.bean.Mensajes;
import dp1.titandevelop.titano.bean.RutaAux;
import dp1.titandevelop.titano.view.prod.ModulosT_PRO_Productos;
import dp1.titandevelop.titano.helper.UnidadMedida;
import dp1.titandevelop.titano.persistent.Almacen;
import dp1.titandevelop.titano.persistent.AlmacenXProducto;
import dp1.titandevelop.titano.persistent.Proceso;
import dp1.titandevelop.titano.persistent.Produccion;
import dp1.titandevelop.titano.persistent.Producto;
import dp1.titandevelop.titano.persistent.ProductoProveedor;
import dp1.titandevelop.titano.persistent.ProductoXProceso;
import dp1.titandevelop.titano.persistent.Proveedor;
import dp1.titandevelop.titano.persistent.Receta;
import dp1.titandevelop.titano.persistent.TipoProducto;
import dp1.titandevelop.titano.service.AlmacenService;
import dp1.titandevelop.titano.service.AlmacenXProductoService;
import dp1.titandevelop.titano.service.ProcesoService;
import dp1.titandevelop.titano.service.ProductoProveedorService;
import dp1.titandevelop.titano.service.ProductoService;
import dp1.titandevelop.titano.service.ProductoXProcesoService;
import dp1.titandevelop.titano.service.ProveedorService;
import dp1.titandevelop.titano.service.RecetaService;
import dp1.titandevelop.titano.service.ValidacionService;
import java.awt.Dimension;
import java.awt.Frame;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Dorita
 */
public class ModulosT_PRO_ProductosEdita1 extends javax.swing.JInternalFrame {
//Servicios
    ProductoService sp = new ProductoService();
    ProductoXProcesoService spp = new ProductoXProcesoService();
    RecetaService sr= new RecetaService();
    ProcesoService ps= new ProcesoService();
    Producto producto;
    
    //private ArrayList<Producto> listaProductos;
    private ArrayList<TipoProducto> listaTipos;
    private List<Proceso> listaProceso;
    private ArrayList<ProductoXProceso> listaProdProEl;
    private ArrayList<Producto> listaInsumos;
    private ArrayList<Receta> listaReceta;
    private ArrayList<Receta> listaRecetaEliminados;
   
    private Mensajes sms = new Mensajes();
    
    private void addList (List<TipoProducto> tipo,List<Proceso> proc,List<String> ums){
        
        for(int i=0;i<tipo.size();i++){
            this.cmbTipoProducto.addItem(tipo.get(i).getDescripcion());
        }
        for(int i=0;i<proc.size();i++){
            this.cmbProceso.addItem(proc.get(i).getDescripcion());
        }
        for(int i=0;i<ums.size();i++){
            this.cmbUM.addItem(ums.get(i));
        }
    }
    /**
     * Creates new form ModulosT_ADM_ProductosNuevo
     */
    
    //Refrescar la tabla de productos
    public ModulosT_PRO_ProductosEdita1(Producto p){
        initComponents();
        ValidacionService val = new ValidacionService();        
        val.SNumeros(this.txtLoteMax);
        val.Longitud(txtLoteMax,7);
        val.SNumeros(this.txtLoteMin);
        val.Longitud(txtLoteMin,4);
        val.SNumeros(this.txtStockMin);
        val.Longitud(txtStockMin,4);
        val.SNumeros(this.txtStockMax);
        val.Longitud(txtStockMax,7);
        val.SNumeros(this.txtDiasVencimiento);
        val.Longitud(txtDiasVencimiento,4);
        val.Longitud(this.txtBeneficio,4);
        val.Longitud(this.txtCosto,4);
        val.Longitud(this.txtPeso,4);
        this.listaInsumos = new ArrayList<Producto>();        
        this.listaProdProEl = new ArrayList<ProductoXProceso>();
        
        this.listaTipos = sp.buscarTodoLosTipos();//new ArrayList<TipoProducto>();
        this.listaProceso=ps.buscarProcAll();
        this.producto =p;
        this.listaReceta= sr.BuscarPorProducto(p);
        this.listaRecetaEliminados=sr.BuscarPorProducto(p);
        for (int i=0;i<listaReceta.size();i++)
        {
            listaInsumos.add(listaReceta.get(i).getToProducto1());
        }
        this.tablaReceta.setModel(this.modeloReceta);
    
        this.listaTipos = sp.buscarTodoLosTipos();//new ArrayList<TipoProducto>();
        this.listaProceso=ps.buscarProcAll();
      
        UnidadMedida u = new UnidadMedida();
        List<String> ums = u.getLista();
        addList(listaTipos,listaProceso,ums);
        
        cmbTipoProducto.setSelectedItem(p.getToTipoProducto().getDescripcion());
        cmbTipoProducto.setEnabled(false);
       
        cmbUM.setSelectedItem(p.getUm());
        cmbProceso.setSelectedItem(p.getToProceso().getDescripcion());
        this.cmbProceso.setEnabled(false);
        this.txtBeneficio.setText(p.getBeneficio().toString());
        this.txtCosto.setText(p.getCosto().toString());
        this.txtDiasVencimiento.setText(p.getDiasvencimiento().toString());
        this.txtLoteMax.setText(p.getLotemaxcompra().toString());
        this.txtLoteMin.setText(p.getLotemincompra().toString());
        this.txtPeso.setText(p.getPeso().toString());
        this.txtProducto.setText(p.getDescripcion());
        this.txtStockMax.setText(p.getStockmax().toString());
        this.txtStockMin.setText(p.getStockmin().toString());
        
        if (1== p.getToTipoProducto().getIdtipoproducto()) {
            txtBeneficio.enable(false);
            txtLoteMin.enable(true);
            txtLoteMax.enable(true);
            this.btnDetalleReceta.setEnabled(false);
            this.btnEliminaReceta.setEnabled(false);
        } else {
            txtBeneficio.enable(true);
            txtLoteMin.enable(false);
            txtLoteMax.enable(false);
            this.btnDetalleReceta.setEnabled(true);
            this.btnEliminaReceta.setEnabled(true);
            
        }
        this.cmbProceso.setEditable(false);
    
    }
    
    
    
    public void RefrescarTablaReceta() {
        
        AbstractTableModel aux = (AbstractTableModel) this.tablaReceta.getModel();
           // this.inhabilitaBotones();
        aux.fireTableDataChanged();
        }
    
   
    
    //Llena nuevos insumos a la lista de receta
    public void Llenar_Insumos(Producto p, float cantidad) {
        listaInsumos.add(p);
        //Crea el objeto receta para pasarlo a la lista a apartir del insumo ingresado
        Receta r =new Receta();
        r.setToProducto1(p);
        r.setUm(p.getUm());
        Estado e=new Estado();
        r.setEstado(e.getActivo());
        r.setCantidad(cantidad);
        listaReceta.add(r);
        
       }
    
    private AbstractTableModel modeloReceta = new AbstractTableModel() { // usando una clase anonima
        // colocando los titulos de las columnas

        String[] titles = {"Insumo", "Cantidad", "UM"};

        public String getColumnName(int col) {
            return titles[col];
        }

        public int getRowCount() {
            return listaReceta.size(); // cuantos registros (filas)
        }

        public int getColumnCount() {
            return 3; // cuantas columnas
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            String res = null;
            Receta r = listaReceta.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    res =r.getToProducto1().getDescripcion();
                    break;
                case 1:
                    res = r.getCantidad().toString();
                    break;
                case 2:
                    res = r.getUm();
                    break;
                            }
            return res;
        }
        //Permite editar la columna de las cantidades
        @Override
            public boolean isCellEditable(int row, int column) {
           
                return ( column == 1 ); 
        }
     
        public void setValueAt(Object value, int row, int col) {
            if ( col == 1 ) {           
                Receta r=listaReceta.get(row);
                r.setCantidad(Float.parseFloat(""+value));
                listaReceta.set(row, r);
            }
            this.fireTableDataChanged();
        };
            
         

        public Receta getValue(int row) {
            return listaReceta.get(row);
        }

        
    };
    
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        btnGuardar = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        lblProducto = new javax.swing.JLabel();
        txtProducto = new javax.swing.JTextField();
        lblTipoProducto = new javax.swing.JLabel();
        cmbTipoProducto = new javax.swing.JComboBox();
        lblStockMin = new javax.swing.JLabel();
        lblLoteMIn = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        lblCosto = new javax.swing.JLabel();
        lblDiasVenc = new javax.swing.JLabel();
        txtDiasVencimiento = new javax.swing.JTextField();
        txtCosto = new javax.swing.JTextField();
        txtPeso = new javax.swing.JTextField();
        txtLoteMin = new javax.swing.JTextField();
        txtStockMin = new javax.swing.JTextField();
        lblStockMax = new javax.swing.JLabel();
        lblLoteMax = new javax.swing.JLabel();
        lblUM = new javax.swing.JLabel();
        lblBeneficio = new javax.swing.JLabel();
        txtStockMax = new javax.swing.JTextField();
        txtLoteMax = new javax.swing.JTextField();
        cmbUM = new javax.swing.JComboBox();
        txtBeneficio = new javax.swing.JTextField();
        pnlReceta = new javax.swing.JPanel();
        jPanel9 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaReceta = new javax.swing.JTable();
        btnEliminaReceta = new javax.swing.JButton();
        btnDetalleReceta = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        cmbProceso = new javax.swing.JComboBox();

        setResizable(true);
        setTitle("Editar Producto");
        setMaximumSize(new java.awt.Dimension(650, 610));
        setMinimumSize(new java.awt.Dimension(650, 610));
        setPreferredSize(new java.awt.Dimension(692, 610));

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/grabar.png"))); // NOI18N
        btnGuardar.setToolTipText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
        btnSalir.setToolTipText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos"));

        lblProducto.setText("Producto");

        txtProducto.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        lblTipoProducto.setText("Tipo Producto");

        cmbTipoProducto.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cmbTipoProducto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbTipoProductoActionPerformed(evt);
            }
        });

        lblStockMin.setText("Stock Min.");

        lblLoteMIn.setText("Lote Min.");

        jLabel2.setText("Peso");

        lblCosto.setText("Costo");

        lblDiasVenc.setText("Dias Vencimiento");

        txtDiasVencimiento.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        txtCosto.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        txtLoteMin.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        txtStockMin.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        lblStockMax.setText("Stock Max.");

        lblLoteMax.setText("Lote Max.");

        lblUM.setText("Unidad Medida");

        lblBeneficio.setText("Beneficio");

        txtStockMax.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        txtLoteMax.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        cmbUM.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccionar" }));
        cmbUM.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbUMActionPerformed(evt);
            }
        });

        txtBeneficio.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblDiasVenc)
                    .addComponent(lblCosto)
                    .addComponent(jLabel2)
                    .addComponent(lblLoteMIn)
                    .addComponent(lblStockMin)
                    .addComponent(lblProducto))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtProducto, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)
                    .addComponent(txtDiasVencimiento)
                    .addComponent(txtCosto)
                    .addComponent(txtPeso)
                    .addComponent(txtLoteMin)
                    .addComponent(txtStockMin))
                .addGap(37, 37, 37)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblTipoProducto)
                    .addComponent(lblStockMax)
                    .addComponent(lblLoteMax)
                    .addComponent(lblUM)
                    .addComponent(lblBeneficio, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(38, 38, 38)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cmbUM, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtLoteMax)
                    .addComponent(txtStockMax)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(cmbTipoProducto, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 11, Short.MAX_VALUE))
                    .addComponent(txtBeneficio))
                .addGap(8, 8, 8))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblProducto)
                    .addComponent(txtProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblTipoProducto)
                    .addComponent(cmbTipoProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblStockMin)
                    .addComponent(txtStockMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblStockMax)
                    .addComponent(txtStockMax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblLoteMIn)
                    .addComponent(txtLoteMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblLoteMax)
                    .addComponent(txtLoteMax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(16, 16, 16)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblCosto)
                            .addComponent(txtCosto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblBeneficio))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblDiasVenc)
                            .addComponent(txtDiasVencimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtPeso)
                            .addComponent(lblUM)
                            .addComponent(cmbUM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtBeneficio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(99, 99, 99)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pnlReceta.setBorder(javax.swing.BorderFactory.createTitledBorder("Receta"));
        pnlReceta.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N
        pnlReceta.setPreferredSize(new java.awt.Dimension(670, 300));

        jPanel9.setBorder(javax.swing.BorderFactory.createTitledBorder("Lista de Insumos"));
        jPanel9.setPreferredSize(new java.awt.Dimension(640, 151));

        tablaReceta.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Descripcion", "Modulo", "Opcion"
            }
        ));
        tablaReceta.setPreferredSize(new java.awt.Dimension(540, 200));
        jScrollPane1.setViewportView(tablaReceta);

        btnEliminaReceta.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/eliminar.png"))); // NOI18N
        btnEliminaReceta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminaRecetaActionPerformed(evt);
            }
        });

        btnDetalleReceta.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/agregar.png"))); // NOI18N
        btnDetalleReceta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDetalleRecetaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
        jPanel9.setLayout(jPanel9Layout);
        jPanel9Layout.setHorizontalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1)
                .addGap(15, 15, 15)
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnEliminaReceta)
                    .addComponent(btnDetalleReceta)))
        );
        jPanel9Layout.setVerticalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel9Layout.createSequentialGroup()
                        .addComponent(btnDetalleReceta)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnEliminaReceta)
                        .addGap(20, 20, 20))
                    .addGroup(jPanel9Layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addContainerGap())))
        );

        jLabel1.setText("Proceso:");

        cmbProceso.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout pnlRecetaLayout = new javax.swing.GroupLayout(pnlReceta);
        pnlReceta.setLayout(pnlRecetaLayout);
        pnlRecetaLayout.setHorizontalGroup(
            pnlRecetaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlRecetaLayout.createSequentialGroup()
                .addGroup(pnlRecetaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlRecetaLayout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cmbProceso, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        pnlRecetaLayout.setVerticalGroup(
            pnlRecetaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlRecetaLayout.createSequentialGroup()
                .addGroup(pnlRecetaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbProceso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(20, 20, 20)
                .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(44, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(pnlReceta, javax.swing.GroupLayout.DEFAULT_SIZE, 664, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(btnGuardar)
                .addGap(4, 4, 4)
                .addComponent(btnSalir)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 243, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlReceta, javax.swing.GroupLayout.DEFAULT_SIZE, 269, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnGuardar, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnSalir, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
  ModulosT_PRO.AdmProductos = new ModulosT_PRO_Productos();
             this.getParent().add(ModulosT_PRO.AdmProductos);
            Dimension desktopSize = this.getParent().getSize();
            Dimension jInternalFrameSize =  ModulosT_PRO.AdmProductos.getSize();
            ModulosT_PRO.AdmProductos.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                    (desktopSize.height - jInternalFrameSize.height)/4 );
            ModulosT_PRO.AdmProductos.show();
            ModulosT_PRO.ventanaPreoductosEdita=null;
            this.dispose();   
    }//GEN-LAST:event_btnSalirActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        // TODO add your handling code here:        
        //Inserta el producto y obtiene id
       ValidacionService val = new ValidacionService(); 
       if (!cmbTipoProducto.getSelectedItem().equals("Insumo")) {
                if(!val.esVacio(this.txtBeneficio)&&
               !val.esVacio(this.txtCosto)&&
               !val.esVacio(this.txtDiasVencimiento)&&
               !val.esVacio(this.txtLoteMax)&&
               !val.esVacio(this.txtLoteMin)&&
               !val.esVacio(this.txtPeso)&&
               !val.esVacio(this.txtProducto)&&
               !val.esVacio(this.txtStockMax)&&
               !val.esVacio(this.txtStockMin)&&
               !val.esCBoxVacio(cmbUM)&&
               !val.esCBoxVacio(cmbTipoProducto)&&!val.esCBoxVacio(this.cmbProceso)&&!this.listaReceta.isEmpty()){ 
        
           try{
                  int idProceso = producto.getToProceso().getIdproceso();

                   //Actualiza datos del proceso:
                   this.sp.actualizar(producto.getIdproducto(), this.txtProducto.getText(), Integer.parseInt(this.txtStockMin.getText()), 
                           Integer.parseInt(this.txtStockMax.getText()), Integer.parseInt(this.txtLoteMin.getText()), 
                           Integer.parseInt(this.txtLoteMax.getText()),Integer.parseInt(this.txtDiasVencimiento.getText()),
                           Float.parseFloat(this.txtBeneficio.getText()), Float.parseFloat(this.txtCosto.getText()), 
                           (String)this.cmbUM.getSelectedItem(), idProceso,
                           Float.parseFloat(this.txtPeso.getText()));


                   //Si es insumo insertar proveedores, si no insertar receta


                   //Primero eliminaremos las recetas eliminadas en la lista:
                   ArrayList<Receta> listaAgregarR = new ArrayList<Receta>();
                   //ArrayList<Receta> listaActualizarR = new ArrayList<Receta>();
                   this.sr.EliminaReceta(listaRecetaEliminados);
                   //Luego seleccionamos los elementos de la lista que seran editados y los que seran agregados
                   for (int i=0; i<this.listaReceta.size();i++)
                   {
                       Receta r = sr.BuscarPorInsumos(producto.getIdproducto(),listaReceta.get(i).getToProducto1().getIdproducto());
                       if (r!=null)
                       {
                           //Editamos los elementos existentes
                           this.sr.ActualizaReceta(r, listaReceta.get(i));
                       }
                       else listaAgregarR.add(listaReceta.get(i));
                   }

                   //Eliminamos los productos x Proceso pertinentes
                   for (int i=0;i<this.listaProdProEl.size();i++)
                   {
                       this.spp.Elimina(listaProdProEl.get(i).getIdproductoxproceso());
                   }

                   //Buscamos los elementos en el que esta presente el producto para obtener sus procesos, orden y productos finales.
                   ArrayList<ProductoXProceso> pp1= this.spp.buscaPorMaterial(producto.getIdproducto(), producto.getToProceso().getIdproceso(), 1);
                   if (!pp1.isEmpty())
                  {//Para todos los nuevos insumos 
                   for (int i=0; i<listaAgregarR.size() ; i++)
                   {
                       for (int j=0; j<pp1.size();j++)//para todos los procesosXproducto implicados
                       {
                           //insertar esa entrada a todos los procesosxproducto
                           this.spp.Inserta(pp1.get(j).getToProceso().getIdproceso(), pp1.get(j).getOrden(), 0,
                                   pp1.get(j).getToProducto1().getIdproducto(),listaAgregarR.get(i).getToProducto1().getIdproducto()); 
                       }
                   }
                   }


               //Luego agregamos los insumos nuevos
               this.sr.Insertar(producto.getIdproducto(), listaAgregarR);
             JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getEditado(),"Mensaje",JOptionPane.INFORMATION_MESSAGE);
               ModulosT_PRO.AdmProductos = new ModulosT_PRO_Productos();
                this.getParent().add(ModulosT_PRO.AdmProductos);
               Dimension desktopSize = this.getParent().getSize();
               Dimension jInternalFrameSize =  ModulosT_PRO.AdmProductos.getSize();
               ModulosT_PRO.AdmProductos.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                       (desktopSize.height - jInternalFrameSize.height)/4 );
               ModulosT_PRO.AdmProductos.show();
               ModulosT_PRO.ventanaPreoductosEdita=null;
               this.dispose();   

           } catch(Exception e) {
                   //e.printStackTrace();
                    JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getError(),"Error",JOptionPane.ERROR_MESSAGE);
              }
          }
          else{
              JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getCompletarCampos(), "Aviso", JOptionPane.WARNING_MESSAGE);
          }
       }
       else 
       {
         if(!val.esVacio(this.txtBeneficio)&&
               !val.esVacio(this.txtCosto)&&
               !val.esVacio(this.txtDiasVencimiento)&&
               !val.esVacio(this.txtLoteMax)&&
               !val.esVacio(this.txtLoteMin)&&
               !val.esVacio(this.txtPeso)&&
               !val.esVacio(this.txtProducto)&&
               !val.esVacio(this.txtStockMax)&&
               !val.esVacio(this.txtStockMin)&&
               !val.esCBoxVacio(cmbUM)&&
               !val.esCBoxVacio(cmbTipoProducto)) 
         {
              try{
                  int idProceso = producto.getToProceso().getIdproceso();

                   //Actualiza datos del proceso:
                   this.sp.actualizar(producto.getIdproducto(), this.txtProducto.getText(), Integer.parseInt(this.txtStockMin.getText()), 
                           Integer.parseInt(this.txtStockMax.getText()), Integer.parseInt(this.txtLoteMin.getText()), 
                           Integer.parseInt(this.txtLoteMax.getText()),Integer.parseInt(this.txtDiasVencimiento.getText()),
                           Float.parseFloat(this.txtBeneficio.getText()), Float.parseFloat(this.txtCosto.getText()), 
                           (String)this.cmbUM.getSelectedItem(), idProceso,
                           Float.parseFloat(this.txtPeso.getText()));
                    JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getEditado(),"Mensaje",JOptionPane.INFORMATION_MESSAGE);
               ModulosT_PRO.AdmProductos = new ModulosT_PRO_Productos();
                this.getParent().add(ModulosT_PRO.AdmProductos);
               Dimension desktopSize = this.getParent().getSize();
               Dimension jInternalFrameSize =  ModulosT_PRO.AdmProductos.getSize();
               ModulosT_PRO.AdmProductos.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                       (desktopSize.height - jInternalFrameSize.height)/4 );
               ModulosT_PRO.AdmProductos.show();
               ModulosT_PRO.ventanaPreoductosEdita=null;
               this.dispose();   

           } catch(Exception e) {
                   //e.printStackTrace();
                    JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getError(),"Error",JOptionPane.ERROR_MESSAGE);
              }
          }
          else{
              JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getCompletarCampos(), "Aviso", JOptionPane.WARNING_MESSAGE);
          }

       }

    }//GEN-LAST:event_btnGuardarActionPerformed

    
    private void cmbTipoProductoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbTipoProductoActionPerformed
        // TODO add your handling code here:
        
    }//GEN-LAST:event_cmbTipoProductoActionPerformed

    private void btnEliminaRecetaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminaRecetaActionPerformed
        // Elimina un detalle de la receta
 // TODO add your handling code here:
        listaRecetaEliminados.add(this.listaReceta.get(tablaReceta.getSelectedRow()));
        
        ArrayList<ProductoXProceso> pp = this.spp.buscaPorMaterial(listaReceta.get(this.tablaReceta.getSelectedRow()).getToProducto1().getIdproducto(),producto.getToProceso().getIdproceso(), 0);
        
        if (!pp.isEmpty()) this.listaProdProEl.addAll(pp);
        listaReceta.remove(this.tablaReceta.getSelectedRow());
        listaInsumos.remove(this.tablaReceta.getSelectedRow());
        this.RefrescarTablaReceta();
    }//GEN-LAST:event_btnEliminaRecetaActionPerformed

    private void btnDetalleRecetaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDetalleRecetaActionPerformed
        // TODO add your handling code here:
        Frame f = JOptionPane.getFrameForComponent(this);
        ModulosT_PRO_BuscarProducto dialog = new ModulosT_PRO_BuscarProducto(f,true, listaInsumos,2, this.producto);
        //this.getParent().add(dialog);
        dialog.setVisible(true);
    }//GEN-LAST:event_btnDetalleRecetaActionPerformed

    private void cmbUMActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbUMActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cmbUMActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDetalleReceta;
    private javax.swing.JButton btnEliminaReceta;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnSalir;
    private javax.swing.JComboBox cmbProceso;
    private javax.swing.JComboBox cmbTipoProducto;
    private javax.swing.JComboBox cmbUM;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JLabel lblBeneficio;
    private javax.swing.JLabel lblCosto;
    private javax.swing.JLabel lblDiasVenc;
    private javax.swing.JLabel lblLoteMIn;
    private javax.swing.JLabel lblLoteMax;
    private javax.swing.JLabel lblProducto;
    private javax.swing.JLabel lblStockMax;
    private javax.swing.JLabel lblStockMin;
    private javax.swing.JLabel lblTipoProducto;
    private javax.swing.JLabel lblUM;
    private javax.swing.JPanel pnlReceta;
    private javax.swing.JTable tablaReceta;
    private javax.swing.JTextField txtBeneficio;
    private javax.swing.JTextField txtCosto;
    private javax.swing.JTextField txtDiasVencimiento;
    private javax.swing.JTextField txtLoteMax;
    private javax.swing.JTextField txtLoteMin;
    private javax.swing.JTextField txtPeso;
    private javax.swing.JTextField txtProducto;
    private javax.swing.JTextField txtStockMax;
    private javax.swing.JTextField txtStockMin;
    // End of variables declaration//GEN-END:variables
}
